<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class VerifyClientBookMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $domain=$request->getScheme()."://".$request->getHttpHost();
        $sign=$request['sign']??null;
        if(empty($sign)){
            return response()->json([
                    'success'=>false,
                    'msg'=>'error sign']);
        }
        $publicKey=$this->readPubKey();
        $obj=[
            "time"=>$request['time'],
            "data"=>$request['data'],
        ];
        $rs = openssl_verify(json_encode(ksort($obj)), base64_decode($sign), $publicKey, OPENSSL_ALGO_SHA256);
        if($rs){
            return $next($request);
        }else{
            return response()->json([
                    "success"=>false,
                    "msg"=>"验证签名失败"
                ]);
        }
    }
    private function readPriKey(){
        $root=dirname(__DIR__);
        $priKeyFile="api_private_key.pem";
        $priKeyPath=$root.'/'.$priKeyFile;
        $f=fopen($priKeyPath,'r');
        $key="";
        while(!feof($f)){
            $key.=fgets($f);
        }
        fclose($f);
        return $key;
    }
    private function readPubKey(){
        $root=dirname(app_path());
        $pubKeyFile="api_public_key.pem";
        $pubKeyPath=$root.'/'.$pubKeyFile;
        $f=fopen($pubKeyPath,'r');
        $key="";
        while(!feof($f)){
            $key.=fgets($f);
        }
        fclose($f);
        return $key;
    }
}
